package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageBean;
import com.zzyl.dto.OrderDto;
import com.zzyl.dto.OrderPageQueryDto;
import com.zzyl.entity.MemberElder;
import com.zzyl.entity.Order;
import com.zzyl.mapper.MemberElderMapper;
import com.zzyl.mapper.OrderMapper;
import com.zzyl.service.OrderService;
import com.zzyl.utils.ThreadLocalUtil;
import com.zzyl.vo.OrderVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private MemberElderMapper memberElderMapper;

    /**
     * 根据订单id获取订单详情
     *
     * @param orderId 订单id
     * @return 订单vo
     */
    @Override
    public OrderVo getOrderById(Long orderId) {
        Order order = orderMapper.selectByPrimaryKey(orderId);
        return BeanUtil.toBean(order, OrderVo.class);
    }

    /**
     * 搜索订单 （小程序端）
     *
     * @return 订单分页vo
     */
    @Override
    public PageBean<OrderVo> searchOrders4Customer(OrderPageQueryDto dto) {
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        Long userId = ThreadLocalUtil.get();
        dto.setUserId(userId);
        Page<Order> lists = orderMapper.searchOrders(dto);
        return PageBean.of(lists, OrderVo.class);
    }


    /**
     * 搜索订单 （管理端）
     *
     * @return 订单分页vo
     */
    @Override
    public PageBean<OrderVo> searchOrders4Manager(OrderPageQueryDto dto) {
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        Page<Order> lists = orderMapper.searchOrders(dto);
        return PageBean.of(lists, OrderVo.class);
    }



    @Override
    public List<OrderVo> listByMemberId(Long id) {
        return orderMapper.listByMemberId(id);
    }

    @Override
    public List<Order> selectByStatus(Integer status) {
        return orderMapper.selectByStatus(status);
    }

    /**
     * 校验老人订单 (小程序端)
     *
     * @param dto
     */
    @Override
    public void checkOlderOrder(OrderDto dto) {
//        1.拿到线程中的用户ID
        Long memberId = ThreadLocalUtil.get();
//        2.拿出老人ID
        Long elderId = dto.getElderId();
//        3.校验用户是否绑定该老人
        List<MemberElder> memberElders = memberElderMapper.listByMemberId(memberId);
        List<Long> elderIds = CollUtil.getFieldValues(memberElders, "elderId", Long.class);
        if (!elderIds.contains(elderId)) {
            throw new RuntimeException("该老人未与您的账号绑定");
        }
//        4.通过校验

    }

    /**
     * 新增老人护理项目订单
     *
     * @param dto
     */
    @Override
    public void addElderOrder(OrderDto dto) {
        Order order = BeanUtil.toBean(dto, Order.class);
        //TODO  给订单生成交易系统订单号

        orderMapper.insert(order);
    }


}

